/*!
 *  @author  xiaody <xiaody09@163.com>
 *  @description  HotKey module.
 */

(function(){


var KeyCodeTable = {
	J : 74, K : 75, O : 79
}

var HotKey = {


	init : function(){

		HotKey.currentFloor = -1;

		if(TiebaWhere.inside) {

			document.addEventListener('keydown', keyListener, true);

			var pos = $$('.l_post');
			for(var i = pos.length, post; i--;) {
				post = pos[i];
				post.order = i;
				if(post.getElementsByTagName('b').length) {
					post.focus();
					HotKey.currentFloor = i;
				}

				post.addEventListener('click', function(e){
					if(e.button === 0 && e.target.tagName !== 'A') {
						pos[HotKey.currentFloor] && pos[HotKey.currentFloor].semiLit();
						this.focus();
						HotKey.currentFloor = this.order;
					}
				}, true);
			}

			pos[0].semiLit();
		}
	}


}


function keyListener(e) {
	"use strict";

	if(document.activeElement !== document.body || e.shiftKey || e.ctrlKey)
		return;

	switch(e.keyCode) {

		// JKscroll
		case KeyCodeTable.J :
			var mainFloor = $$('.l_post')[HotKey.currentFloor + 1];
			if(mainFloor)
				HotKey.currentFloor++;
			else
				return;
			mainFloor.focusIntoView();
			break;
		case KeyCodeTable.K :
			var mainFloor = $$('.l_post')[HotKey.currentFloor - 1];
			if(mainFloor)
				HotKey.currentFloor--;
			else
				return;
			mainFloor.focusIntoView();
			break;

		case KeyCodeTable.O :
			if(HotKey.currentFloor === -1)
				return;
			var mainFloor = $$('.l_post')[HotKey.currentFloor];
				mainFloor.toggle();
			if(mainFloor.attr('bdb_collapse') && mainFloor.next()) {
				mainFloor.next().focusIntoView();
				HotKey.currentFloor++;
			}
			break;
	}

}

window.HotKey = HotKey;


})();